import { defineStore } from "pinia";
import axios from "axios";
import dateFormat from "@/utils/dateFormat.js";
import dayjs from "dayjs";
import { h } from "vue";
import { ElMessageBox, ElNotification } from "element-plus";
// import useSeatStore from "@/store/seat";
// const seatStore = useSeatStore();
import pinia from "@/store/index.js";
import useCommonStore from "@/store/common.js";
const commonStore = useCommonStore(pinia);

const useStore = defineStore({
  id: "flowStore",
  state: () => ({
    loaderType: "real",
    loaderConfig: {
      real: {},
      history: {
        date1: dayjs().subtract(2, "day").toDate(),
        date2: dayjs().subtract(1, "day").toDate(),
        hour1: 4,
        hour2: 4,
      },
      fake: {
        date: dayjs().subtract(1, "day").toDate(),
        equal: false,
        content: {
          zuuu: [240, 240],
          zutf: [430, 430],
          zumy: [45, 45],
        },
        total: 0,
      },
      manual: {
        historyDate: "",
        begTime: "",
        content: [],
      },
      snapshot: {
        from: null,
        to: null,
        pointer: 0,
        content: [],
      },
    },
    loaderConfigAirports: {
      mode: "real",
      autoRefresh: true,
      fakeDate: false,
      customDate: "",
      ignoreWarning: false,
      history: {
        date1: dayjs().subtract(2, "day").toDate(),
        date2: dayjs().subtract(1, "day").toDate(),
        hour1: 4,
        hour2: 4,
      },
    },
    useExperimentPolicy: true,
    useAirportData: false,
    autoRefresh: true,
    ignoreOther: false,
    customDate: "",
    rawData: [],
    flowLimits: [],
    rawDataAirports: [],
    rawRateAirports: [],
    tags: null,
    tagsAirportFlow: null,
    tagsAirportItem: null,
    begTime: "",
    begTimeAirports: "",
    replyData: null,
    replyDataAirports: null,
    classicPolicyScales: null,
    currentSectorScheme: [],
    presetSectorSchemes: [],
    selectedSchemeNumber: -1,
    version: -1,
    versionAirports: -1,
    reference: 0,
    freshness: 0,
    freshnessAirports: 0,
    isStoped: false,
    versionMsg: null,
    ignoreWarning: false,
    fakeDate: false,
    chartConfig: {
      gnenralChart: {
        chartSize: 80,
        chartType: "bar",
        dataGranularity: 2,
        dataInterval: 2,
        dataStep: 2,
        showTotal: true,
        showTotalLine: true,
        showSector: true,
        showSectorLine: true,
        chartStack: true,
        chartEmphasis: false,
        chartFill: false,
        chartPolar: false,
        showConfig: false,
        showSnapshot: false,
      },
      advancedChart: {
        dataGranularity: 2,
        dataInterval: 2,
        dataStep: 2,
        autoPlaySpeed: 1000,
        configBarPinned: true,
        selectedComputingOption: "",
        showConfig: false,
      },
      customChart: {},
      airportsChart: null,
      ratesChart: null,
    },
    airportFlowLimits: null,
    dataQuerierContent: {
      begDate: null,
      endDate: null,
      gap: null,
      response: null,
      responseTime: null,
      arrangedData: null,
      tableColumns: [
        "扇区数量",
        "终端区架次",
        "双流架次",
        "天府架次",
        "活动情况",
      ],
    },
    widgetContent: {
      count: 0,
      result: [],
      resultFiltered: [],
      dataImfo: {},
      limits: [],
      params: {},
      showRawViewer: false,
      showDataViewer: false,
      showLimitsConfig: false,
      showParamsConfig: false,
    },
    chartTemplates: [],
  }),
  getters: {
    seatColors() {
      let colors = {};
      this.currentSectorScheme.forEach((seat) => {
        colors[seat.seatName] = [seat.defaultColor, seat.color];
      });
      return colors;
    },
    sectorSchemes() {
      let content = new Array();
      this.currentSectorScheme.forEach((seat) => {
        content.push({
          seatName: seat.seatName,
          sectorCodes: seat.sectorCodes,
        });
      });
      let data = new Array({
        number: -1,
        title: "当前扇区布局",
        description: "当前生效中的扇区布局",
        type: "当前",
        content,
      });
      if (this.presetSectorSchemes) {
        this.presetSectorSchemes.forEach((s) => data.push(s));
      }
      return data;
    },
    selectedSectorScheme() {
      let scheme = this.sectorSchemes[0];
      if (this.selectedSchemeNumber == -1) {
        return scheme;
      } else {
        for (let i = 0; i < this.presetSectorSchemes.length; i++) {
          if (this.presetSectorSchemes[i].number == this.selectedSchemeNumber) {
            scheme = this.presetSectorSchemes[i];
            break;
          }
        }
      }
      return scheme;
    },
  },
  actions: {
    loadSource() {
      // console.log("loading flow record");
      this.getFlowData();
      this.getAirportFlowData();
      // =================================================
      // 程序已经迁移, 不再通过此方式获取N系统数据
      // =================================================
      // this.loadFlowData().then((reply) => {
      //   if (reply.successed) {
      //     this.getFlowData();
      //   }
      // });
      // this.loadAirportFlowData().then((reply) => {
      //   if (reply.successed) {
      //     this.getAirportFlowData();
      //   }
      // });
      this.loadCurrentSectorScheme();
    },
    getFlowData() {
      // let isSeatAvailable = seatStore.isSeatAvailable;
      // if (!isSeatAvailable) {
      //   this.customDate = dayjs("2023-06-10 00:00:00").toDate();
      // }

      this.replyData = null;
      let timeRange =
        this.customDate !== ""
          ? `&begTime=${dayjs(this.customDate)
              .hour(dayjs().hour())
              .minute(0)
              .second(0)
              .subtract(4, "hour")
              .format("YYYY-MM-DD HH:mm:ss")}&endTime=${dayjs(this.customDate)
              .hour(dayjs().hour())
              .minute(0)
              .second(0)
              .add(20, "hour")
              .format("YYYY-MM-DD HH:mm:ss")} `
          : "";
      // console.log("flowStore / getFlowData / timeRange", timeRange);
      return new Promise((resolve, reject) => {
        axios
          .get(
            "api/flow_ntfm_get.php?" + (this.tags ? "" : "tag=1") + timeRange
          )
          .then((response) => {
            this.rawData = response.data.rawData;
            this.begTime = response.data.begTime;
            this.flowLimits = response.data.flowLimits;
            if (this.fakeDate) {
              let day = dayjs(this.begTime);
              day = day
                .year(dayjs().year())
                .month(dayjs().month())
                .date(dayjs().date());
              if (day.isAfter(dayjs())) {
                day = day.subtract(1, "day");
              }
              this.begTime = day.format("YYYY-MM-DD HH:mm:ss");
            }
            !this.tags && response.data.tags
              ? (this.tags = response.data.tags)
              : null;
            this.replyData = response.data;
            this.version = response.data.version;
            this.reference = response.data.reference;
            this.freshness = response.data.freshness;
            this.isStoped = response.data.isStoped;
            // 演示模式虚拟版本
            if (this.fakeDate || !commonStore.isReal) {
              this.freshness = 1;
              this.version = new Date().getTime();
            }
            this.validVersion(); // valid version @2022-12-11
            resolve(response.data);
          })
          .catch((error) => {
            console.error("getting flow data error", error);
            reject(error);
          });
      });
    },
    getAirportFlowData(manual = false) {
      if (!manual && !this.loaderConfigAirports.autoRefresh) {
        this.replyDataAirports = {
          msg: "autoRefresh is disabled!",
        };
        return new Promise((resolve, reject) => {
          resolve(null);
        });
      } else {
        // let isSeatAvailable = seatStore.isSeatAvailable;
        // if (!isSeatAvailable) {
        //   this.customDate = dayjs("2023-06-10 00:00:00").toDate();
        // }
        this.replyDataAirports = null;
        let timeRange =
          this.customDate !== ""
            ? `&begTime=${dayjs(this.customDate)
                .hour(dayjs().hour())
                .minute(0)
                .second(0)
                .subtract(4, "hour")
                .format("YYYY-MM-DD HH:mm:ss")}&endTime=${dayjs(this.customDate)
                .hour(dayjs().hour())
                .minute(0)
                .second(0)
                .add(20, "hour")
                .format("YYYY-MM-DD HH:mm:ss")} `
            : "";
        // console.log("flowStore / getFlowData / timeRange", timeRange);
        return new Promise((resolve, reject) => {
          axios
            .get(
              "api/flow_ntfm_get_airports.php?" +
                (this.tagsAirportFlow ? "" : "tag=1") +
                timeRange +
                "&tnr=1"
            )
            .then((response) => {
              this.rawDataAirports = response.data.content;
              this.rawRateAirports = response.data.rates;
              this.begTimeAirports = response.data.begTime;
              if (this.fakeDate) {
                let day = dayjs(this.begTime);
                day = day
                  .year(dayjs().year())
                  .month(dayjs().month())
                  .date(dayjs().date());
                if (day.isAfter(dayjs())) {
                  day = day.subtract(1, "day");
                }
                this.begTimeAirports = day.format("YYYY-MM-DD HH:mm:ss");
              }
              if (this.tagsAirportFlow == null && response.data.tags != null) {
                this.tagsAirportFlow = response.data.tags;
              }
              if (
                this.tagsAirportItem == null &&
                response.data.airports != null
              ) {
                this.tagsAirportItem = response.data.airports;
              }
              this.replyDataAirports = response.data;
              this.versionAirports = response.data.version;
              // airportFlowLimits
              this.airportFlowLimits = response.data.limits;
              // this.reference = response.data.reference;
              this.freshnessAirports = response.data.freshness;
              // this.isStoped = response.data.isStoped;
              if (this.fakeDate) {
                this.freshnessAirports = 1;
              }
              this.validVersion(); // valid version @2022-12-11
              resolve(response.data);
            })
            .catch((error) => {
              console.error("getting flow data error", error);
              reject(error);
            });
        });
      }
    },
    validVersion(limit = 10, limit2 = 20) {
      // valid version @2022-12-11
      // let diff = this.freshness / 60;

      // valid version for max TTL @2023-12-30
      let diff = this.freshness / 60;
      let diff2 = this.freshnessAirports / 60;
      if (diff > limit || diff2 > limit2) {
        console.error(`flow data freshness ${diff}s is out of date!`);
        let msg = h("div", null, [
          h(
            "div",
            null,
            `NTFM数据最后更新于${diff.toFixed()}分钟前（${dayjs(
              this.version
            ).format("HH:mm")}）
            ，此后再未成功读取，请尝试采取以下操作进行修复：`
          ),
          h("ol", null, [
            h(
              "li",
              { style: { borderTop: "1px solid rgba(128,128,128,0.5)" } },
              "反复移动总主任席NTFM电脑（最左侧电脑）的鼠标，确认鼠标具有控制权（鼠标可正常移动或屏幕右上角显示“Full Access”提示信息）;"
            ),
            h(
              "li",
              { style: { borderTop: "1px solid rgba(128,128,128,0.5)" } },
              "若以上操作1分钟后问题依旧，总主任席NTFM电脑键盘按Windows徽标键，在弹出菜单中选择“终端”，在终端窗口中输入“/xampp.sh”（不含引号）按回车。"
            ),
          ]),
        ]);
        if (this.versionMsg !== null) {
          this.versionMsg.close();
        }
        if (!this.ignoreWarning) {
          this.versionMsg = ElNotification({
            title: "NTFM数据已中断",
            // message: msg,
            type: "error",
            position: "bottom-right",
            // showClose: false,
            // duration: 1000 * 29,
          });
        }
      }
    },
    loadFlowData(force = 0) {
      this.replyData = null;
      return new Promise((resolve, reject) => {
        axios
          .get(
            `api/flow_ntfm_load.php?force=${force}&ignore=${this.ignoreOther}`
          )
          .then((response) => {
            // console.log("flow data loading", response.data);
            this.replyData = response.data;
            resolve(response.data);
          })
          .catch((error) => {
            console.error("loading NTFM data error", error);
            reject(error);
          });
      });
    },
    loadAirportFlowData(force = 0) {
      this.replyDataAirports = null;
      return new Promise((resolve, reject) => {
        axios
          .get(
            `api/flow_ntfm_load_airports.php?force=${force}&ignore=${this.ignoreOther}`
          )
          .then((response) => {
            // console.log("flow data loading", response.data);
            this.replyDataAirports = response.data;
            resolve(response.data);
          })
          .catch((error) => {
            console.error("loading NTFM airports data error", error);
            reject(error);
          });
      });
    },
    loadCurrentSectorScheme() {
      return new Promise((resolve, reject) => {
        axios
          .get("api/flow_sector_load.php")
          .then((response) => {
            this.currentSectorScheme = response.data;
            resolve();
          })
          .catch((error) => {
            console.error("loading current sector scheme error", error);
            reject();
          });
      });
    },
    loadPresetSectorSchemes() {
      return new Promise((resolve, reject) => {
        axios
          .get("api/flow_sector_preset.php")
          .then((response) => {
            this.presetSectorSchemes = response.data.content;
            resolve(response.data.result);
          })
          .catch((error) => {
            console.error("loading preset sector scheme error", error);
            reject(error);
          });
      });
    },
    saveSectorScheme(scheme) {
      return new Promise((resolve, reject) => {
        axios
          .post("api/flow_sector_preset.php", scheme)
          .then((response) => {
            this.presetSectorSchemes = response.data.content;
            resolve(response.data.result);
          })
          .catch((error) => {
            console.error("saving preset sector scheme error", error);
            reject(error);
          });
      });
    },
    deleteSectorScheme(number) {
      return new Promise((resolve, reject) => {
        axios
          .post("api/flow_sector_preset.php?delete=" + number)
          .then((response) => {
            this.presetSectorSchemes = response.data.content;
            resolve(response.data.result);
          })
          .catch((error) => {
            console.error("deleting preset sector scheme error", error);
            reject(error);
          });
      });
    },
  },
});

export default useStore;
